package cn.jiyun.filter;

import cn.jiyun.common.R;
import com.alibaba.fastjson.JSON;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
@WebFilter(urlPatterns = "/*")
public class LoginFilter implements Filter {

    private AntPathMatcher antPathMatcher=new AntPathMatcher();

    @Override
    public  void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
        //        转换成http请求
        HttpServletRequest request= (HttpServletRequest) servletRequest;
        HttpServletResponse response= (HttpServletResponse) servletResponse;
//        获取请求路径
        String uri=request.getRequestURI();
//        声明需要放行的路径
        String []usrs={"/backend/**","/employee/login"};
        boolean result = checkur(usrs, uri);
        if (result){
            chain.doFilter(request,response);
            return;
        }
        HttpSession session=request.getSession();
        Object employee = session.getAttribute("employee");
        if (employee!=null){
            chain.doFilter(request,response);
            return;
        }
        String notlogin = JSON.toJSONString(R.error("NOTLOGIN"));
        response.getWriter().write(notlogin);

    }

    public boolean checkur(String[]usrs,String uri){
        for (String usr : usrs) {
            if (antPathMatcher.match(usr,uri)){
                return true;
            }
        }
        return false;
    }


}
